package com.apptravel.component;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;



import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


/**
 * �上传实现类.
 * 
 * @author lishsh.
 * 
 *
 */
@Component("upload")
public class UploadImpl implements Upload {
	
	private static final String UPLOAD_CONF_PATH = "classpath:upload.properties";
	
	private static final String UPLOAD_DIR_KEY = "upload.dir";
	
	private static final String UPLOAD_HTTP_KEY = "upload.http";

	/**
	 * 上传实现.
	 * @param request spring上传请求类.
	 * @param type 媒体类型.
	 * 返回文件上传后在服务器的路径地址列表.
	 */
	public List<String> upload(MultipartHttpServletRequest request,MediaType type) {
		Properties pros = new Properties();
		try{
			File confFile = ResourceUtils.getFile(UPLOAD_CONF_PATH);
			InputStream is = new FileInputStream(confFile);
			pros.load(is);
		}catch(Exception e){
			e.printStackTrace();
		}
		List<String> paths = new ArrayList<String>();
		Iterator<String> it = request.getFileNames();
		String uploadPath = pros.getProperty(UPLOAD_DIR_KEY)+StringUtils.lowerCase(type.name())+"/";
		String uploadHttp = StringUtils.lowerCase(type.name())+"/";
		String timenow = System.currentTimeMillis()+"";
		int i = 0;
		while(it.hasNext()){
			String fileName = (String)it.next();
			MultipartFile file = request.getFile(fileName);
			String uploadFileName = file.getOriginalFilename();
			String prefix = uploadFileName.substring(uploadFileName.lastIndexOf("."));
			String newFileName = timenow+i+prefix;
			File newFile = new File(uploadPath+newFileName);
            if(!(new File(uploadPath).exists())){
                new File(uploadPath).mkdirs();
            }
			try{
				file.transferTo(newFile);
				paths.add(uploadHttp+newFileName);
			}catch(Exception e){
				e.printStackTrace();
			}
			i++;
		}
		return paths;
	}
	
	public static void main(String[] arg){
		
	}
	
	
	

}
